<template>

  <div>
    <el-row :gutter="20">
      <el-col :span="16">
        <div class="map">
          <div id="container" style="width: 100%;height: 700px"></div>
        </div>
      </el-col>
      <el-col :span="8">
        <h4>中国地图</h4>
        <div class="home" id="myChartChina" style="height: 42vh"></div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content">
          <div> {{ cityName }}</div>
          <div class="pro" v-for="(p,i) in provinceList" :key="p.id">
            <el-col>
              <el-collapse v-model="activeName" accordion>
                <el-collapse-item :name="i" class="collapse-item">
                  <template slot="title">
                    <div style="display: flex; align-items: center;">
                      <el-button @click="openPoint(p.id)" size="mini" type="primary" plain>编辑</el-button>
                      <span @click="setCenter(p)" style="flex: 1;"> {{ p.name }}</span>
                      <el-button @click="saveFence(i,p.id)" size="mini" type="primary" plain>保存</el-button>
                    </div>
                  </template>
                  <div>与现实生活一致：与现实生活的流程、逻辑保持一致，遵循用户习惯的语言和概念；</div>
                </el-collapse-item>
              </el-collapse>
            </el-col>
          </div>
        </div>
      </el-col>


    </el-row>
  </div>
</template>
<script>
import request from "@/utils/request";

require("echarts/map/json/china.json");
export default {
  props: {},
  data() {
    return {
      activeName: '1',
      cityName: "贵州省",
      map: null,
      provinceList: [],
      //项目
      mapData: [],
      //围栏
      polyEditorList: [],
      project: []
    };
  },

  mounted() {
// 使用自定义函数根据省份名称获取省份信息
    this.getProvinceByProvinceName("贵州省");
// 使用 AMap 库创建一个新地图
    let map = new AMap.Map('container', {
      resizeEnable: true, // 当容器大小改变时自动调整地图大小
      zoom: 11, // 设置地图的初始缩放级别
      center: [106.713478, 26.578343], // 设置地图的初始中心点
      viewMode: '3D', // 将地图视图模式设置为3D
    });
    // 缩放地图到合适的视野级别
    map.setFitView()
    this.map = map;
    this.drawLine()
  },
  methods: {
    //计算中心点
    getPointsCenter(points) {
      let point_num = points.length; //坐标点个数
      let X = 0, Y = 0, Z = 0;
      for (let i = 0; i < points.length; i++) {
        if (points[i] == '') {
          continue;
        }
        let point = points[i].split(',');
        let lat, lng, x, y, z;
        lat = parseFloat(point[0]) * Math.PI / 180;
        lng = parseFloat(point[1]) * Math.PI / 180;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      }
      X = X / point_num;
      Y = Y / point_num;
      Z = Z / point_num;

      let tmp_lng = Math.atan2(Y, X);
      let tmp_lat = Math.atan2(Z, Math.sqrt(X * X + Y * Y));

      return [tmp_lat * 180 / Math.PI, tmp_lng * 180 / Math.PI];
    },

    //保存绘制图形，将数据存入数据库
    saveFence(i, id) {
      let points = this.mapData[i].getPath();
      let data = this.project[i]
      console.log(data)
      let map = []
      let ps = []
      points.forEach(function (point, index) {
        ps.push(point.lat + "," + point.lng)
        map.push((index + 1) + "," + point.lng + "," + point.lat)
      });
      let point = this.getPointsCenter(ps)
      request("project", "post", {
        name: data[0].name,
        map,
        deptId: data[0].deptId,
        latitude: point[0],
        longitude: point[1]
      }).then(() => {
        this.$message.success("修改成功！")
        this.polyEditorList.forEach(map => {
          if (map.has(id)) {
            map.get(id).close()
          }
        })
      }).catch(() => {
        this.$message.error("修改失败！")
      })
    },

    //中心点缩放
    setCenter({
                longitude,
                latitude,
                scale
              }) {
      console.log(longitude)
      this.map.setCenter([longitude, latitude])
      //级别大小
      this.map.setZoom(scale)
    },

   //编辑
    openPoint(id) {
      this.polyEditorList.forEach(map => {
        if (map.has(id)) {
          map.get(id).open()
        } else {
          for (const value of map.values()) {
            value.close()
          }
        }
      })
    },

    //工程项目
    async getPoint(id) {
      // 通过请求获取数据
      let data = await request("project?deptId=" + id);
      data = data.sort((a, b) => a.sort - b.sort);
      this.project.push(data)
      // 将数据转换为路径数组
      let path = [];
      data.forEach(o => {
        path.push([o.longitude, o.latitude]);
      });

      // 创建一个多边形对象
      let polygon = new AMap.Polygon({
        path: path, // 设置多边形的路径
        strokeColor: "#FF33FF", // 设置多边形边框颜色
        strokeWeight: 6, // 设置多边形边框宽度
        strokeOpacity: 0.2, // 设置多边形边框透明度
        fillOpacity: 0.4, // 设置多边形填充透明度
        fillColor: '#1791fc', // 设置多边形填充颜色
        zIndex: 50, // 设置多边形的层级
        bubble: true, // 设置多边形的气泡效果
      });

      // 创建一个多边形编辑器对象
      let polyEditor = new AMap.PolygonEditor(this.map, polygon);

      // 将多边形编辑器对象添加到多边形编辑器列表中
      // this.polyEditorList.push(polyEditor);
      let map = new Map()
      this.polyEditorList.push(map.set(id, polyEditor))

      // 将多边形对象添加到地图数据数组中
      this.mapData.push(polygon);

      // 将多边形对象添加到地图中显示
      this.map.add(this.mapData);

    },


    //根据省名取工程部信息
    async getProvinceByProvinceName(name) {
      // 通过请求获取省份数据
      let data = await request("dept?province=" + name);

      // 清空多边形编辑器列表
      this.polyEditorList = [];
      this.provinceList = data;
      // 移除地图上的所有多边形对象
      this.mapData.forEach(o => {
        this.map.remove(o);
      });

      // 清空地图数据数组
      this.mapData = [];

      // 遍历每个省份数据，调用 getPoint 方法添加多边形对象到地图中
      data.forEach(p => {
        this.getPoint(p.id);
      });
    },

// 异步绘制线条
    async drawLine() {
      // 获取图表容器元素
      let myChartContainer = document.getElementById("myChartChina"); //绑定div容器

      // 定义一个函数来调整图表容器的大小
      let resizeMyChartContainer = function () {
        myChartContainer.style.width = 100 + "%";
        // myChartContainer.style.height = myChartContainer.style.height;
      };

      // 调整图表容器的大小
      resizeMyChartContainer();

      // 初始化 echarts 实例
      let myChartChina = this.$echarts.init(myChartContainer);

      // 通过请求获取城市数据
      let data = await request("city/withCount");

      // 将城市数据转换为适合绘制的格式
      let arr = [];
      data.forEach(({provinceName, cityName, latitude, longitude, value, zoom}) => {
        arr.push({
          provinceName, // 省份名称
          name: cityName, // 城市名称
          value, // 值
          location: [longitude, latitude], // 坐标位置
          zoom: zoom, // 缩放级别
        });
      })

      // 绘制图表
      let optionMap = {
        tooltip: {
          trigger: "item",
        },
        //左侧小导航图标
        visualMap: {
          show: false,
          x: "left",
          y: "center",
          //改变地图区域颜色
          splitList: [
            {start: 1, end: 1000},
            {start: 0, end: 0},
          ],
          color: [
            "#0e94eb",
            "rgba(127,127,127,0.7)",
          ],
        },
        //配置中国地图属性
        series: [
          {
            name: "数据",
            type: "map",
            mapType: "china",
            roam: false,
            label: {
              normal: {
                show: false, //省份名称
              },
              emphasis: {
                show: false,
              },
            },

            data: arr, //数据
          },
        ],
      };
      //地图点击事件（显示省份名字：第三个盒子）
      myChartChina.setOption(optionMap);
      myChartChina.on("click", (params) => {
        this.cityName = params.data.provinceName
        //经纬度
        this.map.setCenter(params.data.location)
        //级别大小
        this.map.setZoom(params.data.zoom)
        console.info(this.map)
        //逻辑控制
        this.getProvinceByProvinceName(params.data.provinceName);
      });
      window.onresize = function () {
        resizeMyChartContainer();
        myChartChina.resize();
      };
    },
  }
};
</script>

<style scoped>
.grid-content {
  height: 43vh;
  text-align: center;
  padding-bottom: 20px;

}

.primary {
  width: 10vh;
}

.home {
  height: 35vh;
  margin-bottom: 10px;
}

.map, .chart {
  height: 600px;
  background: aliceblue;
}

.pro {
  background: white;
  height: 40px;
  padding: 10px;
  margin: 5px;
}

#echart_china {
  width: 100%;
  height: 500px;
  background-color: #f1f3f4;
}
</style>

